<template>
	<view class="tabbar_container">
		<uv-toast ref="homeToast"></uv-toast>
		<uv-navbar placeholder>
			<template v-slot:left>
				<view class="common_flex position_box">
					<uv-icon name="map-fill" color="#3c9cff"></uv-icon>
					<text class="location-text">{{ nearMerchant }}</text>
				</view>
			</template>
		</uv-navbar>
		<!-- <PLoader :loading="loading" backgroundColor="#00000020" /> -->
		<uv-loading-page :loading="loading"></uv-loading-page>

		<VideoCoverGrid ref="videoGrid" />

		<PayCoursesCard ref="payCard"></PayCoursesCard>

		<LoginPopup />

		<CustomTabBar selected="0" />
	</view>
</template>

<script>
	import {
		getUserLocation
	} from '../../utils/location';
	export default {
		data() {
			return {
				loading: false,
				scroll: 0,
				nearMerchant: '',
				freeCourseGrid: {},
				payCourseList: [],
				refreshKey: 0,
			}
		},
		onLoad() {
			this.scroll = uni.getWindowInfo().windowHeight + 'px';
			// 发起用户访问量记录请求
			this.fetchAddViewCount();
			this.fetchUserLocation();
		},
		methods: {
			refresh() {
				// 假设子组件有个initData方法包含created中的逻辑
				this.$refs.videoGrid.initData();
				this.$refs.payCard.handlePayCourses();
			},
			showToast(msg, type, duration) {
				this.$refs.homeToast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			async fetchAddViewCount() {
				try {
					await this.$http.post('/auth/add/view/count');
				} catch (e) {
					console.error(e);
				}
			},
			async fetchUserLocation() {
				try {
					// 获取用户经纬度
					const {
						latitude,
						longitude
					} = await uni.getLocation({
						geocode: true
					});

					if (!latitude || !longitude) {
						throw new Error('获取定位信息失败');
					}


					// 发起请求转换用户经纬度
					const res = await this.$http.get(
						`/wechat/user/near/merchant?latitude=${latitude}&longitude=${longitude}`);

					if (res) {
						this.nearMerchant = '最近门店: ' + res.merchantName + res.name
					} else {
						this.nearMerchant = '暂无最近门店';
					}
				} catch (e) {
					this.showToast('获取位置信息失败', 'default', 1000);
					this.nearMerchant = '暂无位置信息';
				}
			},

		},

		onPullDownRefresh() {
			this.refresh();
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		
		onShow() {
			this.refresh();
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}
</style>

<style lang="scss" scoped>
	@import 'index.scss';
</style>